package com.xframe.xdal.core.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.xframe.xdal.core.annotation.XColumn;
import com.xframe.xdal.core.model.IModel;
import com.xframe.xdal.core.util.XReflect;

import java.lang.reflect.Field;

/**
 * 领域模型的抽象类
 *
 * @author xufeng
 * @version 1.0
 * @date 2023-03-10
 */
public abstract class SysBaseEntity implements IModel {

    public static String FULL_DATA = "ALL";
    public static String BELONG_FULL_DATA = "BELONG_FULL_DATA";
    public static String HASMANY_FULL_DATA = "HASMANY_FULL_DATA";
    @JsonIgnore
    @Override
    public String getEsId() {
        return getObjectId().toString();
    }

    @JsonIgnore
    @Override
    public Object getObjectId() {
        Field field = findPkFieldHelp();
        return XReflect.getFieldValue(this,field);
    }

    @JsonIgnore
    @Override
    public void setObjectId(Object objectId) {
        Field field = findPkFieldHelp();
        XReflect.setFieldValue(this,field,objectId);
    }


    public Field findPkFieldHelp(){
        Field[] fields = XReflect.getFields(this.getClass());
        for(Field field:fields){
            XColumn[] columns = field.getAnnotationsByType(XColumn.class);
            if(columns.length > 0){
                if(columns[0].primaryKeyFlag()){
                    return field;
                }
            }
        }
        return null;
    }

    @Override
    public String findPkField(){
        return findPkFieldHelp().getName();
    }


    @JsonIgnore
    @Override
    public Object getMapkey(){
        return this.getObjectId();
    }

    @Override
    public boolean equals(Object anObject) {
        if (anObject instanceof IModel){
            IModel model = (IModel)anObject;
            return this.getObjectId().equals(model.getObjectId());
        }else {
            return false;
        }
    }

    @Override
    public int hashCode(){

        return this.getObjectId() != null ? this.getObjectId().hashCode() : super.hashCode();
    }
}
